package jp.eisbahn.mgapi.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jp.eisbahn.mgapi.auth.AuthorizationCodeListener;

@SuppressWarnings("serial")
public class AuthorizationCodeServlet extends HttpServlet {

    public static final String AUTHORIZATION_CODE_PARAM_NAME = "code";
    public static final String ERROR_PARAM_NAME = "error";
    
    protected AuthorizationCodeListener authorizationCodeListener;
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String authorizationCode = req.getParameter(AUTHORIZATION_CODE_PARAM_NAME);
        if (authorizationCode != null) {
            authorizationCodeListener.set(authorizationCode);
            return;
        }
        String error = req.getParameter(ERROR_PARAM_NAME);
        if (error != null) {
            authorizationCodeListener.error(error);
            return;
        }
        throw new ServletException("Both code and error parameters not found.");
    }

    public void setAuthorizationCodeListener(AuthorizationCodeListener authorizationCodeListener) {
        this.authorizationCodeListener = authorizationCodeListener;
    }

}
